// ============================================================================
// 移动端抽屉组件
// ============================================================================

import React, { useEffect } from 'react'
import { createPortal } from 'react-dom'
import { XMarkIcon } from '@heroicons/react/24/outline'

export interface MobileDrawerProps {
  isOpen: boolean
  onClose: () => void
  children: React.ReactNode
  title?: string
  position?: 'left' | 'right' | 'top' | 'bottom'
  size?: 'sm' | 'md' | 'lg' | 'full'
  closeOnOverlayClick?: boolean
  closeOnEscape?: boolean
  showCloseButton?: boolean
  className?: string
}

/**
 * 移动端抽屉组件
 */
export function MobileDrawer({
  isOpen,
  onClose,
  children,
  title,
  position = 'left',
  size = 'md',
  closeOnOverlayClick = true,
  closeOnEscape = true,
  showCloseButton = true,
  className = ''
}: MobileDrawerProps) {
  // 处理ESC键关闭
  useEffect(() => {
    if (!isOpen || !closeOnEscape) return

    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        onClose()
      }
    }

    document.addEventListener('keydown', handleEscape)
    return () => document.removeEventListener('keydown', handleEscape)
  }, [isOpen, closeOnEscape, onClose])

  // 防止背景滚动
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = 'hidden'
    } else {
      document.body.style.overflow = 'unset'
    }

    return () => {
      document.body.style.overflow = 'unset'
    }
  }, [isOpen])

  if (!isOpen) return null

  const positionClasses = {
    left: {
      container: 'justify-start',
      drawer: 'h-full animate-slide-right',
      transform: isOpen ? 'translate-x-0' : '-translate-x-full'
    },
    right: {
      container: 'justify-end',
      drawer: 'h-full animate-slide-left',
      transform: isOpen ? 'translate-x-0' : 'translate-x-full'
    },
    top: {
      container: 'items-start',
      drawer: 'w-full animate-slide-down',
      transform: isOpen ? 'translate-y-0' : '-translate-y-full'
    },
    bottom: {
      container: 'items-end',
      drawer: 'w-full animate-slide-up',
      transform: isOpen ? 'translate-y-0' : 'translate-y-full'
    }
  }

  const sizeClasses = {
    sm: position === 'left' || position === 'right' ? 'w-64' : 'h-64',
    md: position === 'left' || position === 'right' ? 'w-80' : 'h-80',
    lg: position === 'left' || position === 'right' ? 'w-96' : 'h-96',
    full: 'w-full h-full'
  }

  const positionConfig = positionClasses[position]

  const handleOverlayClick = (e: React.MouseEvent) => {
    if (e.target === e.currentTarget && closeOnOverlayClick) {
      onClose()
    }
  }

  return createPortal(
    <div 
      className={`fixed inset-0 bg-black bg-opacity-50 z-50 flex ${positionConfig.container} animate-fade-in`}
      onClick={handleOverlayClick}
    >
      <div 
        className={`bg-white dark:bg-gray-800 shadow-xl ${sizeClasses[size]} ${positionConfig.drawer} ${positionConfig.transform} transition-transform duration-300 ${className}`}
        onClick={(e) => e.stopPropagation()}
      >
        {/* 头部 */}
        {(title || showCloseButton) && (
          <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
            {title && (
              <h3 className="text-lg font-medium text-gray-900 dark:text-white">
                {title}
              </h3>
            )}
            {showCloseButton && (
              <button
                onClick={onClose}
                className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
              >
                <XMarkIcon className="w-5 h-5 text-gray-500" />
              </button>
            )}
          </div>
        )}

        {/* 内容 */}
        <div className="flex-1 overflow-auto p-4">
          {children}
        </div>
      </div>
    </div>,
    document.body
  )
}

/**
 * 底部操作表组件
 */
export interface ActionSheetProps {
  isOpen: boolean
  onClose: () => void
  title?: string
  actions: Array<{
    label: string
    onClick: () => void
    variant?: 'default' | 'danger'
    disabled?: boolean
  }>
  cancelText?: string
}

export function ActionSheet({
  isOpen,
  onClose,
  title,
  actions,
  cancelText = '取消'
}: ActionSheetProps) {
  return (
    <MobileDrawer
      isOpen={isOpen}
      onClose={onClose}
      position="bottom"
      size="sm"
      showCloseButton={false}
      className="rounded-t-lg"
    >
      <div className="space-y-2">
        {title && (
          <div className="text-center py-2 border-b border-gray-200 dark:border-gray-700">
            <h3 className="text-sm font-medium text-gray-900 dark:text-white">
              {title}
            </h3>
          </div>
        )}

        <div className="space-y-1">
          {actions.map((action, index) => (
            <button
              key={index}
              onClick={() => {
                action.onClick()
                onClose()
              }}
              disabled={action.disabled}
              className={`w-full py-3 px-4 text-left rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed ${
                action.variant === 'danger'
                  ? 'text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20'
                  : 'text-gray-900 dark:text-white hover:bg-gray-100 dark:hover:bg-gray-700'
              }`}
            >
              {action.label}
            </button>
          ))}
        </div>

        <div className="pt-2 border-t border-gray-200 dark:border-gray-700">
          <button
            onClick={onClose}
            className="w-full py-3 px-4 text-center text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
          >
            {cancelText}
          </button>
        </div>
      </div>
    </MobileDrawer>
  )
}

/**
 * 移动端菜单组件
 */
export interface MobileMenuProps {
  isOpen: boolean
  onClose: () => void
  items: Array<{
    label: string
    icon?: React.ReactNode
    onClick: () => void
    active?: boolean
    badge?: string | number
  }>
}

export function MobileMenu({ isOpen, onClose, items }: MobileMenuProps) {
  return (
    <MobileDrawer
      isOpen={isOpen}
      onClose={onClose}
      position="left"
      size="md"
      title="菜单"
    >
      <nav className="space-y-1">
        {items.map((item, index) => (
          <button
            key={index}
            onClick={() => {
              item.onClick()
              onClose()
            }}
            className={`w-full flex items-center space-x-3 px-3 py-3 rounded-lg transition-colors ${
              item.active
                ? 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400'
                : 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700'
            }`}
          >
            {item.icon && (
              <span className="flex-shrink-0">
                {item.icon}
              </span>
            )}
            <span className="flex-1 text-left font-medium">
              {item.label}
            </span>
            {item.badge && (
              <span className={`px-2 py-1 text-xs rounded-full ${
                item.active
                  ? 'bg-blue-100 dark:bg-blue-800 text-blue-600 dark:text-blue-300'
                  : 'bg-gray-100 dark:bg-gray-600 text-gray-600 dark:text-gray-300'
              }`}>
                {item.badge}
              </span>
            )}
          </button>
        ))}
      </nav>
    </MobileDrawer>
  )
}
